import Organization from "@/components/common/replace/sellWorkOrderDepartment";
import selectUser from "@/components/common/selectUser/selectUser";
import iuSelector from "@/components/common/selector/selector";
import { XImg, Selector, Confirm } from "vux";
import SafetyManageDao from "@/daos/safety_manage_dao";
import FileUpload from "@/daos/file_upload";
import upload from "@/components/common/upload/upload";

import dayjs from "dayjs";

const AssignmentsDataMixin = {
  data() {
    return {
      confirmShow: false,
      esignShow: false,
      esignTargrt: "",
      esignContent: "",
      esignUrl: "",
      buttonShow: true,
      selectUserShow: false,
      confirmRejectTag: false,
      selectUserData: null,
      selectUserType: "user",
      loading: false,
      fileList: [],
      form: {
        taskLevel: "",
        // 危害辨识
        hazardIdentification: [],
        // 安全措施 选择的
        safetyMeasures: [],
        // 安全措施 选择的
        safetyMeasuresContent: [],
        // 安全措施确认人
        safetyMeasuresPerson: [],
        // 验收人
        acceptancePerson: [],
        person: [
          {
            person: "",
            personId: "",
            workType: "",
            workCode: ""
          }
        ],
        analysis: [
          {
            person: "",
            personId: "",
            time: "",
            point: "",
            content: ""
          }
        ]
      },
      levelOption: [
        { label: "特级", value: "特级" },
        { label: "一级", value: "一级" },
        { label: "二级", value: "二级" },
        { label: "三级", value: "三级" }
      ],
      hazardOption: [
        { label: "物体打击", value: "物体打击" },
        { label: "车辆伤害", value: "车辆伤害" },
        { label: "机械伤害", value: "机械伤害" },
        { label: "起重伤害", value: "起重伤害" },
        { label: "触电", value: "触电" },
        { label: "淹溺", value: "淹溺" },
        { label: "灼烫", value: "灼烫" },
        { label: "火灾", value: "火灾" },
        { label: "高处坠落", value: "高处坠落" },
        { label: "坍塌", value: "坍塌" },
        { label: "冒顶片帮", value: "冒顶片帮" },
        { label: "透水", value: "透水" },
        { label: "放炮", value: "放炮" },
        { label: "火药爆炸", value: "火药爆炸" },
        { label: "瓦斯爆炸", value: "瓦斯爆炸" },
        { label: "锅炉爆炸", value: "锅炉爆炸" },
        { label: "容器爆炸", value: "容器爆炸" },
        { label: "其他爆炸", value: "其他爆炸" },
        { label: "中毒和窒息", value: "中毒和窒息" },
        { label: "其他伤害", value: "其他伤害" }
      ]
    };
  },
  props: {
    typeList: Array,
    view: String
  },
  created() {
    this.init();
  },
  computed: {
    user() {
      return this.$store.state.user;
    },
    userServiceArea() {
      if (this.$store.state.user) {
        let serviceAreaTree = this.$store.state.user.serviceAreaTree;
        serviceAreaTree.departmentName = "选择部门";
        serviceAreaTree.id = "";
        return serviceAreaTree;
      } else {
        return {};
      }
    },
    safeExamineDetail() {
      return this.$store.state.safetyCheck.safeExamineDetail;
    },
    curEsignUser() {
      let item = this.safeExamineDetail.approvalProcessDetail.find(
        e => e.userId == (this.user && this.user.id) && e.checkState == null
      );
      return item;
    },
    isEdit() {
      return (
        (this.safeExamineDetail.state === 1 ||
          this.safeExamineDetail.state === 3) &&
        this.safeExamineDetail.userId === (this.user && this.user.id)
      );
    },
    isSignature() {
      return (
        this.safeExamineDetail.state === 4 || this.safeExamineDetail.state === 2
      );
    },
    isEsign() {
      let res = this.safeExamineDetail.approvalProcessDetail
        .filter(e => e.operateType && e.checkState == null)
        .some(e => e.userId == (this.user && this.user.id));
      // && this.curEsignUser && !this.curEsignUser.checkState;
      return res;
    },
    acceptancePerson() {
      return this.safeExamineDetail.approvalProcessDetail.filter(
        e => e.sequence
      );
    },
    safetyMeasuresPerson() {
      return this.safeExamineDetail.approvalProcessDetail.filter(
        e => !e.sequence
      );
    }
  },
  watch: {
    safeExamineDetail: {
      handler: function() {
        if (this.safeExamineDetail.id) {
          this.init();
        }
      },
      immediate: true,
      deep: true
    }
  },
  components: {
    Organization,
    XImg,
    Selector,
    Confirm,
    selectUser,
    upload,
    iuSelector
  },
  methods: {
    init() {
      if (this.safeExamineDetail.id) {
        Object.assign(this.form, JSON.parse(this.safeExamineDetail.content));
      } else if (this.user) {
        this.form.applyDepartmentName = this.user.department.departmentName;
        this.form.applyDepartmentId = this.user.department.id;
        this.form.applyPerson = this.user.name;
        this.form.applyPersonId = this.user && this.user.id;
        this.form.acceptancePerson = this.acceptancePersonData.map((e, i) => {
          return {
            sequence: i + 1,
            person: "",
            personId: ""
          };
        });
      }
    },
    back() {
      this.$router.go(-1);
    },
    departmentSelected(params, target) {
      if (!!params.id) {
        this.$set(this.form, `${target}DepartmentId`, params.id);
        this.$set(this.form, `${target}DepartmentName`, params.departmentName);
      }
    },
    eventPersonAdd() {
      this.form.person.push({
        person: "",
        personId: "",
        workType: "",
        workCode: ""
      });
    },
    eventPersonRemove(index) {
      this.form.person.splice(index, 1);
    },
    eventAnalysisAdd() {
      this.form.analysis.push({
        person: "",
        personId: "",
        time: "",
        point: "",
        content: ""
      });
    },
    eventAnalysisRemove(index) {
      this.form.analysis.splice(index, 1);
    },
    eventPersonSelect(userType = "user", ...data) {
      if (this.isSignature) {
        return;
      }
      this.selectUserShow = true;
      this.selectUserData = data;
      this.selectUserType = userType;
    },
    handlePersonSelected(data) {
      let [tag, index, target] = this.selectUserData;
      if (target) {
        if (!this.form[tag][index]) {
          this.$set(this.form[tag], index, {});
        }
        this.$set(this.form[tag][index], target, data.name);
        this.$set(this.form[tag][index], `${target}Id`, data.id);
      } else {
        this.$set(this.form, tag, data.name);
        this.$set(this.form, `${tag}Id`, data.id);
      }
    },
    eventReject() {
      // this.confirmShow = true;
      this.esignShow = true;
      this.confirmRejectTag = true;
    },
    handleReject() {
      let params = {
        approvalProcessId: this.curEsignUser.id,
        saftAppId: this.safeExamineDetail.id,
        signatureList: [
          {
            checkState: 0,
            content: this.esignContent,
            contentType: 0,
            id: this.curEsignUser.approvalRecordId,
            url: ""
          }
        ]
      };

      SafetyManageDao.postSafeExamineSignature(params, res => {
        this.$vux.toast.show({ text: "驳回成功！", type: "success" });
        this.esignShow = false;
        this.confirmShow = false;
        this.back();
      });
    },
    selectTime(tag, index, target) {
      if (this.isSignature) {
        return;
      }
      let _this = this;
      let now = dayjs();
      this.$vux.datetime.show({
        cancelText: "取消",
        confirmText: "确定",
        format: "YYYY-MM-DD HH:mm",
        startDate: now.format("YYYY-MM-DD"),
        onConfirm(value) {
          if (target) {
            _this.$set(_this.form[tag][index], target, +dayjs(value));
          } else {
            _this.$set(_this.form, tag, +dayjs(value));
          }
        },
        onHide(type) {
          if (type === "cancel") {
          }
        }
      });
    },
    eventConfirm(state) {
      let list = document.querySelectorAll(".checkbox-list");
      this.form.safetyMeasuresContent.splice(0);
      list.forEach(e => {
        let res = e.getAttribute("data-list");
        if (
          (res && (this.form.safetyMeasures.includes(res) || res == "p")) ||
          !this.form.safetyMeasures.length
        ) {
          let text = e.innerText;
          if (text.includes("请选择")) {
            return;
          }
          if (text.includes("其他安全措施") && this.form.safetyMeasuresOther) {
            this.form.safetyMeasuresContent.push(
              text + this.form.safetyMeasuresOther
            );
            return;
          }
          this.form.safetyMeasuresContent.push(text);
        }
      });
      let approvalProcess = [];
      this.form.safetyMeasuresPerson.forEach(e => {
        let res = approvalProcess.some(ele => ele.userId === (e && e.personId));
        if (!res && e && e.personId) {
          approvalProcess.push({
            message: "",
            sequence: 100,
            userId: e.personId
          });
        }
      });

      if (!approvalProcess.length) {
        this.$vux.toast.show({ text: "请选择确认人", type: "warn" });
        return;
      }

      let size = 0;
      this.form.acceptancePerson.forEach((e, i) => {
        if (e && e.personId) {
          size++;
          approvalProcess.push({
            message: "",
            sequence: i + 100 + 1,
            userId: e.personId
          });
        }
      });

      if (size !== this.form.acceptancePerson.length) {
        this.$vux.toast.show({ text: "验收人请选择完整", type: "warn" });
        return;
      }

      let type = this.typeList.findIndex(e => e.key === this.view);
      let name = this.typeList[type].value;
      let params = {
        id: this.isEdit ? this.safeExamineDetail.id : null,
        approvalProcess,
        code: this.safeExamineDetail.code,
        content: JSON.stringify(this.form),
        departmentId: this.form.applyDepartmentId,
        endTime: this.form.endTime,
        grade: this.form.taskLevel,
        name,
        place: this.form.taskPlace,
        process: 0,
        state,
        orgId: this.user.org.id,
        startTime: this.form.startTime,
        type: type + 1,
        userId: this.form.applyPersonId
      };
      let text = "";
      // if (!params.grade) {
      //   text = "请选择作业级别";
      // } else
      if (!params.startTime || !params.endTime) {
        text = "请选择作业时间";
      }

      if (text) {
        this.$vux.toast.show({ text, type: "warn" });
        return;
      }

      SafetyManageDao[this.isEdit ? "putSafeExamine" : "postSafeExamine"](
        params,
        res => {
          this.$vux.toast.show({ text: "保存成功！", type: "success" });
          this.back();
        }
      );
    },
    handleEsignReset() {
      // this.$refs.esign.reset();
      this.esignShow = false;
    },
    handleShowCancel() {
      this.esignShow = false;
      this.confirmRejectTag = false;
    },
    handleShowConfirm() {
      if (!this.confirmRejectTag) {
        this.$refs.esign
          .generate()
          .then(res => {
            this.confirmShow = true;
          })
          .catch(err => {
            this.$vux.toast.show({ text: "请签字", type: "warn" });
          });
      } else if (this.confirmRejectTag && !this.esignContent) {
        this.$vux.toast.show({ text: "请输入内容", type: "warn" });
        return;
      } else {
        this.confirmShow = true;
      }
    },
    handleTipsConfirm() {
      if (this.confirmRejectTag) {
        this.handleReject();
      } else {
        this.handleEsignConfirm();
      }
    },
    eventEsignConfirm() {
      this.esignShow = true;
    },
    async handleEsignConfirm() {
      let formData = new FormData();
      let files = await this.$refs.esign
        .generate()
        .then(res => {
          return res;
        })
        .catch(err => {
          this.$vux.toast.show({ text: "请签名", type: "warn" });
          return "";
        });
      if (!files) {
        return;
      }
      formData.append("file", files);
      this.esignUrl = await FileUpload.uploadBase(formData);
      if (!this.esignUrl) {
        this.$vux.toast.show({ text: "上传失败", type: "warn" });
      }

      let params = {
        approvalProcessId: this.curEsignUser.id,
        saftAppId: this.safeExamineDetail.id,
        signatureList: [
          {
            checkState: 1,
            content: this.esignContent,
            contentType: 0,
            id: this.curEsignUser.approvalRecordId,
            url: this.esignUrl
          }
        ]
      };
      // console.log(params);
      SafetyManageDao.postSafeExamineSignature(params, res => {
        this.$vux.toast.show({ text: "保存成功！", type: "success" });
        this.esignShow = false;
        this.confirmShow = false;
        this.back();
      });
    },
    eventShowImg(url) {
      this.$emit("onShowImg", url);
    },
    oversize() {
      this.$vux.toast.text("文件大小请不要超过5MB。");
    },
    overcount() {
      this.$vux.toast.text("文件个数请小于2个。");
    },
    deleteList(index) {
      this.fileList.splice(index, 1);
    },
    async afterRead(files, type) {
      let formData = new FormData();
      formData.append("file", files);
      this.loading = true;
      let res = await FileUpload.uploadBase(formData);
      this.loading = false;
      if (res) {
        this.form[type] = res;
        this.fileList.splice(0, this.fileList.length, res);
      } else {
        this.$vux.toast.text("上传失败");
      }
    }
  }
};

export default AssignmentsDataMixin;
